package cool.webstudy.admin.exception;

import cool.webstudy.admin.constant.enums.rescode.CommonResCodeEnum;
import cool.webstudy.admin.utils.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.text.MessageFormat;

/**
 * @author 莫振双
 * @date 2024/7/15 23:38
 * @description: 异常处理切面类
 */
@Slf4j
@RestControllerAdvice
public class CustomExceptionHandler {
    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result handleBusinessException(BusinessException e) {
        if (ArrayUtils.isNotEmpty(e.getExtendMessage())) {
            String msg = e.getResCodeEnum().msg();
            msg = MessageFormat.format(msg, e.getExtendMessage());
            return Result.failure(e.getResCodeEnum(), msg, e);
        }
        //返回错误信息
        return Result.failure(e.getResCodeEnum(), e);
    }

    /**
     * 处理系统异常
     */
    @ExceptionHandler(SystemException.class)
    public Result handleSystemException(SystemException e) {
        //返回错误信息
        return Result.failure(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result handleMissingServletRequestParameterException(MissingServletRequestParameterException e){
        log.error(e.getMessage(), e);
        String msg = MessageFormat.format(CommonResCodeEnum.RC_PARAM_MISS.msg(),e.getParameterName());
        return Result.failure(CommonResCodeEnum.RC_PARAM_MISS.code(),msg);
    }

    /**
     * 处理其他异常
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        log.error(e.getMessage(), e);
        //处理未知异常信息
        return Result.failure(CommonResCodeEnum.RC_UNKNOWN_ERROR.code(),e.getMessage());
    }
}
